<?php

declare(strict_types=1);

namespace app\admin\logic\server;

use app\common\model\server\Sentence;
use app\admin\logic\system\SysUserLogic;
use app\admin\logic\server\ChatsLogic;
use app\api\controller\Event;

/**
 * 问候语列表
 */
class SentenceLogic
{
    /**
     * @notes 问候语列表
     * @param array $param
     * @return \think\response\Json
     */
    public static function lists(array $param)
    {
        $list = Sentence::custom($param)
            ->with('service')
            ->order('id desc')
            ->pages($param)
            ->select();
        return list_fmt($list, Sentence::custom($param)->count());
    }
    //发送欢迎语
    public static function getSentence($kefu_id,$uid,$is_reply=1){
        
        if($is_reply==3) return false;
        $sentence=self::getAll(['kefu_id'=>$kefu_id]);
        if(count($sentence)==0){
            $content='您好，有什么需要咨询的吗？';
        }else{
            $rand= count($sentence)>0 && $is_reply==2 ? rand(0,count($sentence)-1) : 0;
            $content=$sentence[$rand]['content'];
        }
        if(!cache($kefu_id.'_welcome_'.$uid)){
            $da=[
                'content'=>$content,
                'direction'=>2,
                'fileType'=>'text',
                'kefu_id'=>$kefu_id,
                'uid'=>$uid
            ];
            ChatsLogic::edit($da);
            cache($kefu_id.'_welcome_'.$uid,1);
        }
        //查询历史记录
        $msglist=ChatsLogic::getMsgList($uid);
        
        $server=SysUserLogic::details(['id'=>$kefu_id]);
        return Event::sendUid($uid,['type'=>'welcome','msg'=>'欢迎语','data'=>$content,'time'=>time(),'kefu_id'=>$kefu_id,'msglist'=>$msglist,'server'=>$server]);
    }
     /**
     * @notes 编辑问候语
     * @param array $param
     * @return bool
     */
    public function edit(array $param)
    {
        $param['content']=strip_tags($param['content']);
        return !empty($param['id']) ? Sentence::update($param) : Sentence::create($param);
    }
    /**
     * @notes 删除问候语
     * @param integer $id
     * @return bool
     */
    public function delete($id)
    {
        return Sentence::whereIn('id',$id)->delete();
    }
    public static function getAll($where){
        return Sentence::where($where)->select();
    }
}
